package com.java.computeronline.model.blo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.java.computeronline.model.entity.Manufacturer;
import com.java.computeronline.model.entity.ProductUnit;

public class ProductUnitBLO {
	@SuppressWarnings("unchecked")
	public List<ProductUnit> list(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<ProductUnit> units = null;
		Query query = pm.newQuery(ProductUnit.class);
		units = (List<ProductUnit>)query.execute();
		return units;
	}
	
	public ProductUnit getById(Long id){
		ProductUnit unit = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			unit = pm.getObjectById(ProductUnit.class, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
		}
		return unit;
	}
	
	public ProductUnit add(ProductUnit unit) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(unit);
        }catch(Exception ex){
        	ex.printStackTrace();
        } finally {
            pm.close();
        }
		return unit;
	}
	
	public ProductUnit delete(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProductUnit productUnit;
		try {
			pm.currentTransaction().begin();
			productUnit = pm.getObjectById(ProductUnit.class, id);
            pm.deletePersistent(productUnit);
            pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return productUnit;
	}
	
	public ProductUnit update(ProductUnit unit){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProductUnit productUnit;
		try {
			pm.currentTransaction().begin();
			productUnit = pm.getObjectById(ProductUnit.class, unit.getId());
			productUnit.setTitle(unit.getTitle());
            pm.makePersistent(productUnit);
			pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return productUnit;
	}
}
